<template>
  <div class="my-day-container">
    <n-layout>
      <n-layout-header bordered>
        <div class="header-content">
          <h1>我的一天</h1>
          <div class="header-actions">
            <n-button secondary @click="goToTaskList">
              返回任务列表
            </n-button>
            <n-button type="primary" @click="showCreateTaskModal = true">
              <template #icon>
                <n-icon><Add /></n-icon>
              </template>
              新建任务
            </n-button>
            <n-button @click="handleLogout">
              退出
            </n-button>
          </div>
        </div>
      </n-layout-header>
      
      <n-layout-content class="content">
        <!-- 任务列表 -->
        <div class="task-list" v-if="tasks.length > 0">
          <n-list>
            <n-list-item v-for="task in tasks" :key="task.task_id">
              <n-thing>
                <template #header>
                  <div class="task-header">
                    <n-checkbox
                      :checked="task.status === 2"
                      @update:checked="(val: boolean) => toggleTaskStatus(task, val)"
                    />
                    <span :class="{ 'task-completed': task.status === 2 }">{{ task.title }}</span>
                    <n-tag v-if="task.is_important" type="error" size="small">重要</n-tag>
                  </div>
                </template>
                <template #description>
                  <div class="task-description">
                    {{ task.description }}
                  </div>
                  <div class="task-meta">
                    <span>{{ formatDate(task.created_at) }}</span>
                    <span v-if="task.due_date">截止: {{ formatDate(task.due_date) }}</span>
                  </div>
                </template>
                <template #header-extra>
                  <n-button text @click="goToTaskDetail(task.task_id)">
                    <n-icon><Create /></n-icon>
                  </n-button>
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
        </div>
        
        <!-- 空状态 -->
        <div class="empty-state" v-else>
          <n-empty description="暂无'我的一天'任务">
            <template #extra>
              <n-button type="primary" @click="showCreateTaskModal = true">
                创建任务
              </n-button>
            </template>
          </n-empty>
        </div>
      </n-layout-content>
    </n-layout>
    
    <!-- 创建任务模态框 -->
    <n-modal v-model:show="showCreateTaskModal" preset="dialog" title="新建任务">
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
      >
        <n-form-item label="任务标题" path="title">
          <n-input v-model:value="formValue.title" placeholder="请输入任务标题" />
        </n-form-item>
        <n-form-item label="任务描述" path="description">
          <n-input
            v-model:value="formValue.description"
            type="textarea"
            placeholder="请输入任务描述"
          />
        </n-form-item>
        <n-form-item label="所属分组" path="group_id">
          <n-select
            v-model:value="formValue.group_id"
            :options="groupSelectOptions"
            placeholder="请选择分组"
          />
        </n-form-item>
        <n-form-item label="截止日期" path="due_date">
          <n-date-picker
            v-model:value="formValue.due_date"
            type="date"
            placeholder="请选择截止日期"
          />
        </n-form-item>
        <n-form-item label="重要性">
          <n-checkbox v-model:checked="formValue.is_important">
            标记为重要
          </n-checkbox>
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showCreateTaskModal = false">取消</n-button>
        <n-button type="primary" @click="handleCreateTask" :loading="loading">确定</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import { Add, Create } from '@vicons/ionicons5'

// 导入所有使用的Naive UI组件
import {
  NLayout,
  NLayoutHeader,
  NLayoutContent,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NCheckbox,
  NDatePicker,
  NTag,
  NThing,
  NList,
  NListItem,
  NModal,
  NIcon,
  NEmpty
} from 'naive-ui'

import { useTaskStore } from '../../stores/taskStore'
import { useGroupStore } from '../../stores/groupStore'
import { useUserStore } from '../../stores/userStore'
import type { Task } from '../../types/task'
import type { TaskGroup } from '../../types/group'

const router = useRouter()
const message = useMessage()
const taskStore = useTaskStore()
const groupStore = useGroupStore()
const userStore = useUserStore()

// 状态
const showCreateTaskModal = ref(false)
const loading = ref(false)

// 表单引用
const formRef = ref<FormInst | null>(null)

// 表单数据
const formValue = ref({
  title: '',
  description: '',
  group_id: null as number | null,
  due_date: null as number | null,
  is_important: false,
  is_my_day: true // 默认添加到我的一天
})

// 表单规则
const rules: FormRules = {
  title: {
    required: true,
    message: '请输入任务标题',
    trigger: 'blur'
  },
  group_id: {
    required: true,
    message: '请选择所属分组',
    trigger: 'blur'
    // 移除type属性，因为会导致类型错误
  }
}

// 计算属性
const tasks = computed(() => taskStore.getMyDayTasks)

const groupSelectOptions = computed(() => {
  return groupStore.getAllGroups.map((group: TaskGroup) => ({
    label: group.name,
    value: group.group_id
  }))
})

// 方法
const goToTaskList = () => {
  router.push('/tasks')
}

const goToTaskDetail = (taskId: number) => {
  router.push(`/tasks/${taskId}`)
}

const toggleTaskStatus = (task: Task, checked: boolean) => {
  const newStatus = checked ? 2 : 0
  taskStore.updateTask(task.task_id, { status: newStatus })
}

const handleCreateTask = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        loading.value = true
        // 处理日期格式
        const taskData = {
          ...formValue.value,
          due_date: formValue.value.due_date 
            ? new Date(formValue.value.due_date).toISOString().split('T')[0] 
            : undefined
        }
        
        const result = await taskStore.createTask(taskData)
        if (result.success) {
          message.success('任务创建成功')
          showCreateTaskModal.value = false
          
          // 重新获取"我的一天"任务列表以确保数据一致性
          await taskStore.fetchMyDayTasks()
          
          // 重置表单
          formValue.value = {
            title: '',
            description: '',
            group_id: null,
            due_date: null,
            is_important: false,
            is_my_day: true
          }
        } else {
          message.error(result.message || '任务创建失败')
        }
      } catch (error) {
        message.error('任务创建过程中发生错误')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(async () => {
  await taskStore.fetchMyDayTasks()
  await groupStore.fetchGroups()
})
</script>

<style scoped>
.my-day-container {
  height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.content {
  padding: 16px;
}

.task-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-completed {
  text-decoration: line-through;
  color: #999;
}

.task-description {
  margin-top: 4px;
  color: #666;
}

.task-meta {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>